package com.swang.pms.web.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swang.pms.common.util.HttpUtil;
import com.swang.pms.common.util.ThreadLocalUtil;
import com.swang.pms.model.entity.ManageUser;
import com.swang.pms.model.constants.CommonConstants;

/**
 * AuthFilter.java
 * 
 * @description 验证控制拦截
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        CommonConstants.BASE_PATH_FULL = HttpUtil.getBasePath(httpRequest);
        if (isExpPath(httpRequest.getRequestURL().toString())) {
            chain.doFilter(request, response);
        } else {
            Object obj = session.getAttribute(CommonConstants.SESSION_USER_KEY);
            if (obj != null) {
                ThreadLocalUtil.setAdmin((ManageUser) obj);
                chain.doFilter(request, response);
            } else {
                //1:判断是否是ajax请求
                if (httpRequest.getHeader("x-requested-with") != null
                        && "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("x-requested-with"))) {
                    //向http头添加 状态 sessionStatus
                    httpResponse.setHeader("sessionStatus", "NO_ADMIN");
                    chain.doFilter(request, response);
                    return;
                }
                httpResponse.sendRedirect(CommonConstants.BASE_PATH_FULL + CommonConstants.LOGIN_PATH);
            }
        }
    }

    @Override
    public void destroy() {
    }

    private boolean isExpPath(String url) {
        for (int i = 0; i < CommonConstants.EXCEPT_PATH.length; i++) {
            if (url.indexOf(CommonConstants.BASE_PATH_FULL + CommonConstants.EXCEPT_PATH[i]) == 0) {
                return true;
            }
        }
        return false;
    }
}
